package com.zss.staff.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zss.pojo.Employee;
import com.zss.staff.service.EmployeeService;
import com.zss.utils.HttpClient;
import com.zss.utils.WechatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;

@Controller
@RequestMapping("staff/employee")
public class EmployeeController {

    @Resource
    EmployeeService employeeService;

    @RequestMapping("toAdd")
    public String list(Model model){
        return "staff/employee/add";
    }

    @RequestMapping("selectByOpenId")
    @ResponseBody
    public Employee selectByOpenId(@RequestParam("openId")String openId){
        LambdaQueryWrapper<Employee> queryWarpper = new LambdaQueryWrapper<Employee>();
        queryWarpper.eq(Employee::getOpenid,openId);
        Employee one = employeeService.getOne(queryWarpper);
        return one;
    }

    @RequestMapping("save")
    @ResponseBody
    public void save(@RequestBody Employee employee,HttpServletRequest request){

        if(employee.getId()==null){
            LambdaQueryWrapper<Employee> queryWarpper = new LambdaQueryWrapper<Employee>();
            queryWarpper.eq(Employee::getName,employee.getName());
            queryWarpper.eq(Employee::getPhone,employee.getPhone());
            Employee one = employeeService.getOne(queryWarpper);
            if(one!=null){ // 手机号和姓名不为空，变成更新
                employee.setId(one.getId());
            }
        }

        String openId = (String) request.getSession().getAttribute("openId");
        employee.setOpenid(openId);
        employee.setStatus("0");
        employeeService.saveOrUpdate(employee);
    }

    @RequestMapping("toLogin")
    public String toLogin(){
        return "staff/employee/login";
    }

    @RequestMapping("login")
    @ResponseBody
    public String login(HttpServletRequest request, @RequestBody Employee employee){
        LambdaQueryWrapper<Employee> querWarpper = new LambdaQueryWrapper<Employee>();
        querWarpper.eq(Employee::getName,employee.getName());
        querWarpper.eq(Employee::getPhone,employee.getPhone());
        Employee one = employeeService.getOne(querWarpper);
        if(one==null){
            return "5000";
        }
        if(one.getStatus().equals("2")){
            return "4000";
        }
        request.getSession().setAttribute("employeeUserId",one.getId());
        return "2000";
    }

    @RequestMapping("getInfo")
    @ResponseBody
    public Employee getInfo(HttpServletRequest request){
        String openId = (String) request.getSession().getAttribute("openId");
        LambdaQueryWrapper<Employee> queryWarpper = new LambdaQueryWrapper<Employee>();
        queryWarpper.eq(Employee::getOpenid,openId);
        Employee one = employeeService.getOne(queryWarpper);
        System.out.println("-----------");
        System.out.println(one);
        System.out.println("=======");
        return one;
    }


    @RequestMapping("authorizeCheck/{flag}")
    public String authorizeCheck(Model model, @PathVariable String flag){
        System.out.println("=========");
        System.out.println(flag);
        System.out.println("----------");
        model.addAttribute("flag",flag);
        return "staff/authorize";
    }

    @RequestMapping("noauthor")
    public String noauthor(){
        return "staff/employee/noauthor";
    }

    @RequestMapping("locks")
    public String locks(){
        return "staff/employee/locks";
    }

    @RequestMapping("checkSignature")
    @ResponseBody
    public String checkSignature(HttpServletRequest request){

        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        System.out.println("signature="+signature+"=timestamp="+timestamp+"=nonce="+nonce+"=echostr="+echostr);

        return echostr;
    }


    @RequestMapping("authorize/{flag}")
    public void authorize(@PathVariable String flag, HttpServletRequest request, HttpServletResponse response){

        System.out.println("=====authorize=========authorize=========");

//        String openId = (String) request.getSession().getAttribute("openId");
//        System.out.println("=====openId====="+openId);
//        if(StringUtils.isBlank(openId)){
//            System.out.println("=====StringUtils.isBlank(openId)=====");
//            WechatUtils wechatUtils = new WechatUtils();
//            wechatUtils.authorize();
            String authorizeUrl = WechatUtils.authorizeUrl.replace("APPID",WechatUtils.appid)
                    .replace("REDIRECT_URI", URLEncoder.encode(WechatUtils.codeUrl))
                    .replace("SCOPE",WechatUtils.scopeSnsapiBase)
                    .replace("STATE",flag);
            System.out.println(authorizeUrl);
            try {
                response.sendRedirect(authorizeUrl);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
//        }
    }

    @RequestMapping("getCode")
    public String getCode(@RequestParam("code")String code,@RequestParam("state")String state,
                        HttpServletRequest request,HttpServletResponse response,Model model){
        System.out.println("========getCode========="+code);
        WechatUtils wechatUtils = new WechatUtils();
        String openId = wechatUtils.getOpenId(code);
        System.out.println("======getCode==openId======="+openId);
        request.getSession().setAttribute("openId",openId);
//        try {
//            System.out.println("+++++++++++++++++++++++++");
//            System.out.println("+++++++++++++++++++++++++");
//            System.out.println("+++++++++++++++++++++++++");
//            System.out.println("+++++++++++++++++++++++++");
//            response.sendRedirect("https://www.krwl.top/staff/employee/authorizeCheck/"+state);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        model.addAttribute("flag",state);
        return "staff/authorize";
    }

    @RequestMapping("getOpenId")
    @ResponseBody
    public boolean getOpenId(HttpServletRequest request){
        String openId = (String) request.getSession().getAttribute("openId");
        System.out.println("--------getOpenId---------"+openId);
        if(StringUtils.isBlank(openId)){
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String accessTokenUrl = WechatUtils.accessTokenUrl.replace("APPID",WechatUtils.appid)
                .replace("APPSECRET",WechatUtils.appsecret);
        HttpClient client = new HttpClient(accessTokenUrl);
        try {
            client.get();
            String content = client.getContent();
            JSONObject jsonObject = JSON.parseObject(content);
            String access_token = (String) jsonObject.get("access_token");
            System.out.println(access_token);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }


}
